#!/usr/bin/env Rscript

# main.R - Render Rmd file in Docker environment for R 4.4.3
# This script renders a specified Rmd file from the Scripts directory

# If we are in a renv environment, activate and restore it. Detect the `renv.lock` file.
if (file.exists("renv.lock")) {
    renv::restore(prompt = FALSE)
}




# Configuration variable - specify which Rmd file to render
RMD_FILE <- "AEA-Annual-Report_reproducible.Rmd"

# Set up the environment
cat("Starting R main script...\n")
cat("R version:", R.version.string, "\n")

rootdir <- here::here()

message("Working directory :", rootdir)

# Define paths
scripts_dir <- file.path(rootdir, "Scripts")
rmd_path <- file.path(scripts_dir, RMD_FILE)

# Verify that the Rmd file exists
if (!file.exists(rmd_path)) {
  stop("Error: Rmd file not found at: ", rmd_path)
}

message("Found Rmd file:", rmd_path)

# Load required packages
required_packages <- c("rmarkdown", "knitr")

for (pkg in required_packages) {
  if (!require(pkg, character.only = TRUE, quietly = TRUE)) {
    cat("Installing package:", pkg, "\n")
    install.packages(pkg)
    library(pkg, character.only = TRUE)
  }
}

# Set up output directory
output_dir <- file.path(rootdir, "Output")
if (!dir.exists(output_dir)) {
  dir.create(output_dir, recursive = TRUE)
}

setwd(scripts_dir)  # Change working directory to Scripts for rendering
message("Rendering Rmd file:", RMD_FILE)

# Render the Rmd file
tryCatch({
  # Render with output to the Output directory
  output_file <- rmarkdown::render(
    input = RMD_FILE,
    output_dir = output_dir,
    output_format = "all",
    clean = TRUE,
    quiet = FALSE
  )
  
  message("Successfully rendered Rmd file!")
  
}, error = function(e) {
  cat("Error rendering Rmd file:", e$message, "\n")
  setwd(rootdir)  # Restore working directory
  quit(status = 1)
})

# Restore original working directory
setwd(rootdir)

message("Rendering complete. Check the Output directory for results.")
